import { Injectable } from '@nestjs/common'
import { ConfigService } from '@nestjs/config'
import { Server } from 'socket.io'

interface Room {
  id: string
  name: string
  ownerId: string
  category?: string
  createdAt: Date
  updatedAt: Date
}

@Injectable()
export class RoomService {
  private rooms: Room[] = []

  constructor(private readonly io: Server, private readonly configService: ConfigService) {}

  async createRoom(ownerId: string, roomData: any): Promise<Room> {
    const newRoom = {
      id: Math.random().toString(36).substr(2, 9),
      name: roomData.name,
      ownerId,
      category: roomData.category,
      createdAt: new Date(),
      updatedAt: new Date(),
    }
    this.rooms.push(newRoom)
    return newRoom
  }

  async getRoomList(options: {
    page: number
    limit: number
    category?: string
  }): Promise<{ rooms: Room[]; total: number }> {
    const { page, limit, category } = options
    const filteredRooms = category
      ? this.rooms.filter((room) => room.category === category)
      : this.rooms

    const startIndex = (page - 1) * limit
    const endIndex = page * limit
    const paginatedRooms = filteredRooms.slice(startIndex, endIndex)

    return {
      rooms: paginatedRooms,
      total: filteredRooms.length,
    }
  }

  async getRoomInfo(roomId: string): Promise<Room | null> {
    return this.rooms.find((room) => room.id === roomId) || null
  }

  async updateRoom(roomId: string, userId: string, updateData: any): Promise<Room | null> {
    const roomIndex = this.rooms.findIndex((room) => room.id === roomId && room.ownerId === userId)

    if (roomIndex === -1) return null

    this.rooms[roomIndex] = {
      ...this.rooms[roomIndex],
      ...updateData,
      updatedAt: new Date(),
    }

    return this.rooms[roomIndex]
  }

  async joinRoom() {
    // TODO: 实现加入房间逻辑
  }

  async leaveRoom() {
    // TODO: 实现离开房间逻辑
  }
}
